<template>
  <div class="search flex flex-s">
    <div class="input-container relative">
      <input
        ref="inputRef"
        v-model="keyword"
        type="text"
        placeholder="输入标题或网址"
        @focus="visible = true"
        @keydown="find"
        @click="visible = true"
      />

      <div v-if="visible" ref="dom" class="triggle">
        <History v-if="results.length > 0" :results="results"></History>
        <SmartSuggestion v-else :keyword="keyword"> </SmartSuggestion>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { Ref, onMounted, ref } from 'vue';
  import { Folder } from '@/types/global';
  import { selectList } from '@/views/bus';
  import { onClickOutside } from '@vueuse/core';
  import History from './history/History.vue';
  import SmartSuggestion from './smart-suggestion/SmartSuggestion.vue';

  const inputRef = ref();

  const dom = ref();
  const keyword = ref<string>('');
  const visible = ref(false);

  const results = ref<Folder[]>([]);
  onMounted(() => {
    const inputEl = inputRef.value as HTMLInputElement;
    inputEl.onfocus = () => {
      inputEl.select();
    };
  });

  const find = () => {
    results.value = [];

    if (!keyword.value) return;
    const searchTree = (tree: Folder[], kw: string, res: Ref): void => {
      // eslint-disable-next-line no-restricted-syntax
      for (const node of tree) {
        if (node.title.includes(kw) || (node.link && node.link.includes(kw))) {
          res.value.push(node);
        }
        if (node.type === 'folder' && node.children) {
          searchTree(node.children, kw, res);
        }
      }
    };
    if (!selectList.value) return;
    searchTree(selectList.value, keyword.value, results);
  };

  onClickOutside(dom, () => {
    visible.value = false;
  });
</script>

<style lang="scss" scoped>
  .search {
    height: 90px;
    background-color: #eee;
    background: url('./background.webp');
    background-repeat: no-repeat;
    background-size: cover;

    .input-container {
      width: clamp(400px, 40%, 40vw);
      height: 36px;
      max-width: 400px;
      input {
        width: 100%;
        height: 100%;
        border-radius: 18px;
        text-align: center;
        &:hover {
          border: 2px solid #000;
        }
      }
    }
    .triggle {
      position: absolute;
      width: 100%;
      height: fit-content;
      top: calc(100% + 10px);
      background-color: #f5f2f3;
      box-shadow: 0 0 25px #80808038;
      border-radius: 12px;
      overflow: hidden;
      z-index: 10;
      max-height: 40vh;
      overflow-y: auto;
    }
  }
</style>
